const db = require('../config/db');
const bcrypt = require('bcryptjs');

class User {
    // 创建用户
    static async create(phone, password) {
        try {
            // 检查手机号是否已存在
            const [existingUsers] = await db.execute(
                'SELECT * FROM t_user WHERE phone = ?',
                [phone]
            );

            if (existingUsers.length > 0) {
                throw new Error('该手机号已被注册');
            }

            // 加密密码
            const salt = await bcrypt.genSalt(10);
            const hashedPassword = await bcrypt.hash(password, salt);

            // 生成用户ID
            const userId = Date.now().toString();

            // 插入新用户
            const [result] = await db.execute(
                `INSERT INTO t_user (
                    user_id, username, password, phone, nickname, 
                    gender, level, experience, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [
                    userId,
                    phone, // 默认使用手机号作为用户名
                    hashedPassword,
                    phone,
                    phone, // 默认使用手机号作为昵称
                    0, // 默认性别为未知
                    1, // 默认等级为1
                    0, // 默认经验值为0
                    1  // 默认状态为正常
                ]
            );

            return userId;
        } catch (error) {
            throw error;
        }
    }

    // 通过手机号查找用户
    static async findByPhone(phone) {
        try {
            const [users] = await db.execute(
                'SELECT * FROM t_user WHERE phone = ?',
                [phone]
            );
            return users[0];
        } catch (error) {
            throw error;
        }
    }

    // 验证密码
    static async verifyPassword(password, hashedPassword) {
        try {
            const isMatch = await bcrypt.compare(password, hashedPassword);
            return isMatch;
        } catch (error) {
            throw error;
        }
    }

    // 更新最后登录时间
    static async updateLastLoginTime(userId) {
        try {
            await db.execute(
                'UPDATE t_user SET last_login_time = NOW() WHERE user_id = ?',
                [userId]
            );
        } catch (error) {
            throw error;
        }
    }
}

module.exports = User;